<template>
  <div>
    <!-- 用户信息弹窗 -->
    <el-dialog v-model="userDataVisible" title="用户信息" width="40%" draggable class="user-box"
      :before-close="changeChartVisible">
      <div class="nav-bar">
        <el-button @click="addUser">
          <el-icon>
            <Plus />
          </el-icon>新增
        </el-button>
        <span>
          <el-input placeholder="请输入用户名" v-model="queryContent" @keyup.enter="sreachUserData" />
          <el-button-group>
            <el-button :icon="Refresh" @click="updata" />
            <el-button :icon="Grid" />
          </el-button-group>
        </span>
      </div>
      <el-table border style="width: 100%" :data="pagingData">
        <el-table-column prop="username" label="用户名" width="120" align="center">
        </el-table-column>
        <el-table-column label="用户类型" width="120" align="center">
          <template #default="{ row }">
            {{ typeData(row) }}
          </template>
        </el-table-column>
        <el-table-column label="登录状态" width="120" align="center">
          <template #default="{ row }">
            {{ row.isOnline ? "登录" : "下线" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <div class="btn" v-show="!(row.type === 'admin')">
              <el-button type="success" size="small" @click="modifyUserData(row)">
                修改</el-button>
              <el-button type="danger" size="small" @click="deleteData(row)">
                删除</el-button>
              <el-button type="warning" size="small" v-show="row.isOnline" @click="offline(row)">
                下线</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination small background layout="prev, pager, next" :default-page-size="pageSise" :total="showData.length"
        v-model:current-page="currentPage" />
    </el-dialog>
  </div>
  <!-- 新增用户和修改用户弹窗 -->
  <div>
    <el-dialog v-model="inputUserVisible" :title='titleData' width="40%" draggable class="message-box">
      <div class="content">
        <div class="input-box">
          <span v-if="titleData==='新增交通部门用户'">用户名</span>
          <span v-else>新用户名</span>
          <el-input placeholder="请输入用户名" v-model.trim="userName" />
        </div>
        <div class="input-box">
          <span v-if="titleData==='新增交通部门用户'">密码</span>
          <span v-else>新密码</span>
          <el-input placeholder="请输入密码" v-model.trim="userPassword" />
        </div>
      </div>
      <div class="footer-btn">
        <el-button type="primary" @click="confirm(titleData)"> 确定</el-button>
        <el-button @click="cancel"> 取消</el-button>
      </div>
    </el-dialog>
  </div>

  <!-- 删除确定弹窗 -->
  <div>
    <el-dialog v-model="deleteVisible" title='删除用户' width="40%" draggable class="message-box">
      <div class="content">
        这个一个<span>{{ typeData(data) }}</span>的账号,删除可能导致该用户无法访问网站,是否确定要删除
      </div>
      <div class="footer-btn">
        <el-button type="primary" @click="delUser"> 确定</el-button>
        <el-button @click="deleteVisible = false"> 取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { Grid, Refresh, Plus } from "@element-plus/icons-vue";
import { onMounted, ref } from "vue";
import {
  queryUserHttp,
  registerHttp,
  deleteUserHttp,
  offlineUserHttp,
  reviseUserData,
  changeUserPassword
} from "../../../request/api";
const props = defineProps(["changeChartVisible"])
//弹窗的开关
const userDataVisible = ref(true);
const inputUserVisible = ref(false);
const deleteVisible = ref(false)
//显示数据
const allUserData = ref([]);
const showData = ref([]);
const pageSise = 10;
const currentPage = ref(1);
const titleData = ref('')
//输入的数据
const userName = ref("");
const userPassword = ref("");
const queryContent = ref("");
//暂时存储的数据
const data = ref()
onMounted(() => {
  getUserData()
})
//获取用户数据
async function getUserData() {
  const type = ["admin", "traffic", "common"];
  const getData = [];
  for (const item of type) {
    try {
      const res = await queryUserHttp(item);
      res.data.result.forEach((item) => {
        getData.push(item);
      });
    } catch (error) { }
  }
  allUserData.value = getData;
  showData.value = allUserData.value;
}
//新增用户
function addUser() {
  titleData.value = '新增交通部门用户'
  inputUserVisible.value = true;
}
//确定增加用户
function confirmAddUser() {
  registerHttp({
    username: userName.value.trim().replaceAll(" ", ""),
    password: userPassword.value,
    type: "traffic",
  }).then((res) => {
    if (res.data.code !== 200) {
      ElMessage({
        message: res.data.msg,
        type: "warning",
      });
      return;
    }
    ElMessage({
      message: res.data.msg,
      type: "success",
    });
    cancel()
  });
  userName.value = "";
  userPassword.value = "";
}

//确定按钮
function confirm(data) {
  if (userName.value === "") {
    ElMessage({
      showClose: true,
      message: "用户名为空,请重新输入",
      type: "warning",
    });
  } else if (userPassword.value === "") {
    ElMessage({
      showClose: true,
      message: "密码为空,请重新输入",
      type: "warning",
    });
  } else if (data === '新增交通部门用户') {
    confirmAddUser()
  } else if (data === '修改用户信息') {
    confirmModifyData()
  }

}
//取消按钮
function cancel() {
  userName.value = "";
  userPassword.value = "";
  inputUserVisible.value = false;
}
//搜寻用户信息
function sreachUserData() {
  if (queryContent.value === "登录") {
    queryContent.value = true;
  } else if (queryContent.value === "下线") {
    queryContent.value = false;
  } else if (queryContent.value === "管理员") {
    queryContent.value = 'admin';
  } else if (queryContent.value === "交通部门") {
    queryContent.value = 'traffic';
  } else if (queryContent.value === "普通用户") {
    queryContent.value = 'common';
  }

  const sreachdata = allUserData.value.filter((item) =>
    Object.values(item).some((val) => val == queryContent.value)
  );
  if (sreachdata.length === 0) {
    ElMessage({
      showClose: true,
      message: "未查询到结果",
      type: "warning",
    });
  } else {
    showData.value = sreachdata;
  }
  queryContent.value = "";
}
//刷新页面
function updata() {
  getUserData();
}
//点击修改
function modifyUserData(item) {
  titleData.value = '修改用户信息'
  inputUserVisible.value = true;
  data.value = item
}
//确定修改数据
function confirmModifyData() {
  const id = data.value.id
  const info = {
    username:data.value.username,
    password:data.value.password,
    newName:userName.value.trim().replaceAll(" ", ""),
    newPassword:userPassword.value,
    type:data.value.type
  }
  changeUserPassword(info).then((res) => {
    if (res.data.code !== 200) {
      ElMessage({
        message: res.data.msg,
        type: "warning",
      });
      return;
    }
    ElMessage({
      message: res.data.msg,
      type: "success",
    });
    cancel()
  });
  userName.value = "";
  userPassword.value = "";
}
// function confirmModifyData() {
//    const id=data.value.id
//     reviseUserData(id,{
//       username: userName.value.trim().replaceAll(" ", ""),
//       password: userPassword.value,
//     }).then((res) => {
//       if (res.data.code !== 200) {
//         ElMessage({
//           message: res.data.msg,
//           type: "warning",
//         });
//         return;
//       }
//       ElMessage({
//         message: res.data.msg,
//         type: "success",
//       });
//     });
//      userName.value = "";
//   userPassword.value = ""; 
// }
//点击删除按钮
function deleteData(item) {
  deleteVisible.value = true
  data.value = item
}
//删除用户
function delUser() {
  const user = {
    type: data.value.type,
    username: data.value.username,
  };
  deleteUserHttp(user).then((res) => {
    if (res.data.code !== 200) {
      ElMessage({
        message: res.data.msg,
        type: "warning",
      });
      return;
    }
    ElMessage({
      message: res.data.msg,
      type: "success",
    });
  });
  deleteVisible.value = false
  getUserData();
}
//退出登录
function offline(item) {
  const user = {
    type: item.type,
    username: item.username,
  };
  offlineUserHttp(user).then((res) => {
    if (res.data.code !== 200) {
      ElMessage({
        message: res.data.msg,
        type: "warning",
      });
      return;
    }
    ElMessage({
      message: res.data.msg,
      type: "success",
    });
  });
  getUserData();
}
//计算分页数据
const pagingData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSise;
  const endIndex = startIndex + pageSise;
  return showData.value.slice(startIndex, endIndex);
});
//将类型转换成字符串
function typeData(item) {
  if (item.type === 'admin') {
    return '管理员'
  } else if (item.type === "traffic") {
    return '交通部门'
  } else if (item.type === "common") {
    return '普通用户'
  }
}
</script>

<style lang="scss" scoped>
.user-box {
  .nav-bar {
    display: flex;
    justify-content: space-between;

    .el-input {
      width: 200px;
      margin-right: 10px;
    }
  }

  .el-table {
    margin: 10px 0;
  }

  .el-pagination {
    display: flex;
    justify-content: flex-end;
  }
}

.message-box {
  .content {
    margin-bottom: 20px;

    .input-box {
      margin-bottom: 20px;
      margin-left: 80px;
      display: flex;
      justify-content: space-between;

      span {
        font-weight: 900;
        line-height: 2em;
      }

      .el-input {
        width: 80%;
      }
    }
  }

  .footer-btn {
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-dialog__body) {
  border-top: 1px solid rgb(220, 217, 217);
  padding-top: 15px;
}
</style>
